// ignore_for_file: prefer_typing_uninitialized_variables, non_constant_identifier_names, unnecessary_new, unused_import, unnecessary_const, prefer_const_constructors, must_be_immutable, library_private_types_in_public_api, use_build_context_synchronously, prefer_interpolation_to_compose_strings

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:customer_log_app/global/console.dart';
import 'package:customer_log_app/global/global.dart';
import 'package:customer_log_app/global/log_helper.dart';
import 'package:customer_log_app/global/sqlite_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

// import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class Home extends StatefulWidget {
  bool desktop;

  Home({super.key, required this.desktop});

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  late List<Widget> swipers = [];
  late List<Widget> posterTypes = [];
  late List<Widget> posterList = [];
  late List<dynamic> posterItems = [];
  late List<dynamic> oldItems = [];
  int page = 0;

  double leftHight = 0;
  double rightHeight = 0;
  double itemWidth = 0;
  List<dynamic> leftList = [];
  List<dynamic> rightList = [];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  getSwipers() async {
    Global.showLoading(context);
    try {
      final result = await Global().dio.get("app/ad/");

      List<Widget> imgTest = [];

      if (result.statusCode == 200) {
        var rs = result.data['data'];
        log('swiper');
        log(rs);
        for (var i = 0; i < rs.length; i++) {
          String url = rs[i]['image_url'].toString();
          imgTest.add(
            Container(
              margin: const EdgeInsets.only(
                  left: 10, right: 10, top: 10, bottom: 10),
              child: Container(
                decoration: ShapeDecoration(
                  //设置圆角
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadiusDirectional.circular(20)),
                ),
                //设置边距
                margin: const EdgeInsets.only(left: 10, right: 10),
                // child: const Card(
                //   color: Colors.transparent,
                // ),
                child: getImage(url),
              ),
            ),
          );
        }

        setState(() {
          swipers = imgTest;
        });
      }
      // ignore: empty_catches
    } catch (e) {}
    Global.hideLoading(context);
  }

  getOtherData() async {
    Global.showLoading(context);
    try {
      var result = await Global().dio.get("app/poster/types?page=0");

      var phoneSize = MediaQuery.of(context).size;
      List<Widget> posterTypesList = [];
      double categoryHeight = 50;
      double categoryWidth = phoneSize.width - 40;

      if (result.statusCode == 200) {
        var rs = result.data['data'];
        log('types');
        log(rs);
        for (var i = 0; i < rs.length; i++) {
          String url = rs[i]['image_url'].toString();
          posterTypesList.add(
            GestureDetector(
              child: Column(
                children: [
                  Container(
                    width: categoryWidth / 5,
                    height: categoryHeight,
                    //设置边距
                    margin: const EdgeInsets.only(left: 0, right: 0, top: 0),

                    // child: Image(
                    //   image: getImage(url),
                    // ),
                    child: getImage(url),
                  ),
                  SizedBox(
                    height: 20,
                    child: Text(
                      rs[i]['name'].toString(),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.black,
                        fontFamily: Global.baseFont,
                      ),
                    ),
                  ),
                ],
              ),
              onTap: () {
                log('type:${rs[i]['id']}');
                // gotoCategory(rs[i]['id'].toString(), rs[i]['name'].toString());
              },
            ),
          );
        }

        var url = '${Global.baseUrl}mini/images/category-all.png';
        posterTypesList.add(
          GestureDetector(
            child: Column(
              children: [
                Container(
                  width: categoryWidth / 5,
                  height: categoryHeight,
                  //设置边距
                  margin: const EdgeInsets.only(left: 0, right: 0, top: 0),
                  // child: Container(
                  //   decoration: ShapeDecoration(
                  //     image: DecorationImage(
                  //       //设置背景图片

                  //       image: NetworkImage(url),
                  //       fit: BoxFit.fill,
                  //     ),
                  //     //设置圆角
                  //     shape: RoundedRectangleBorder(
                  //         borderRadius: BorderRadiusDirectional.circular(10)),
                  //   ),
                  //   //设置边距
                  //   margin: const EdgeInsets.only(left: 0, right: 0, top: 0),
                  //   child: const Card(
                  //     color: Colors.transparent,
                  //   ),
                  // ),
                  child: Image(
                    image: NetworkImage(url),
                  ),
                ),
                SizedBox(
                  height: 20,
                  child: Text(
                    'بارلىق',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                      fontFamily: Global.baseFont,
                    ),
                  ),
                ),
              ],
            ),
            onTap: () {
              log('type:0');
              // gotoCategory('0', 'بارلىق');
            },
          ),
        );

        setState(() {
          posterTypes = posterTypesList;
        });
      }
      // ignore: empty_catches
    } catch (e) {}

    Global.hideLoading(context);
  }

  addPosterDataToSqlite(List<dynamic> allData) async {
    if (1 == 1) {
      return 0;
    }
    SqliteHelper sqlHelper = SqliteHelper();
    var now = Global.dateFormat(DateTime.now(), '-', '-');
    for (var i = 0; i < allData.length; i++) {
      String sql = 'select * from posters where id = ' +
          allData[i]['id'].toString() +
          ' and created_at datetime(' +
          now +
          ')';
      sql = 'select * from posters where id = ' + allData[i]['id'].toString();
      List<Map> dt = await sqlHelper.getData(sql);
      log('check sql:  id:' +
          allData[i]['id'].toString() +
          ' ,count:' +
          dt.length.toString());
      log('data?' + dt.length.toString());
      if (dt.isEmpty) {
        //insert
        Map<String, Object?> data = {
          'id': int.parse(allData[i]['id'].toString()),
          'name': allData[i]['name'] ?? '',
          'poster': allData[i]['poster'],
          'poster_height': int.parse(allData[i]['poster_height'].toString()),
          'poster_url': allData[i]['poster_url'],
          'poster_width': int.parse(allData[i]['poster_width'].toString()),
          'type_id': int.parse(allData[i]['type_id'].toString()),
          'created_at': now,
          'updated_at': now,
        };
        try {
          sqlHelper.insertData('posters', data);
        } catch (e) {
          log('insert error');
          log(e);
        }
      } else {
        //update
        String nm = allData[i]['name'] ?? '';
        sql = " update posters set ";
        if (nm.isEmpty) {
          sql += " poster='" + allData[i]['poster'] + "'";
        } else {
          sql += " name ='" + nm + "'";
          sql += ",poster='" + allData[i]['poster'] + "'";
        }

        sql += ",poster_height=" + allData[i]['poster_height'].toString();
        sql += ",poster_url = '" + allData[i]['poster_url'] + "'";
        sql += ",poster_width =" + allData[i]['poster_width'].toString();
        sql += ",type_id = " + allData[i]['type_id'].toString();
        sql += ",updated_at = '" + now + "'";
        sql += " where id=" + allData[i]['id'].toString();
        try {
          sqlHelper.updateData(sql);
        } catch (e) {
          log('update error');
          log(e);
        }
      }
    }
  }

  getStoredItems() async {
    SqliteHelper sqlHelper = SqliteHelper();
    String sql = 'select * from posters';
    List<Map> dt = await sqlHelper.getData(sql);
    return dt;
  }

  getItems() async {
    log('get posters:$page');
    Global.showLoading(context);
    String url = "app/poster/list?page=$page";
    log(url);
    var allData;
    try {
      try {
        log('check stored item');
        var data = await getStoredItems();
        log('stored data length:' + data.length.toString());
      } catch (e1) {
        log('getStoreditems error');
        log(e1);
      }
      var result = await Global().dio.get(url);

      var phoneSize = MediaQuery.of(context).size;
      bool flag = true;
      flag = result.statusCode == 200;
      if (flag) {
        allData = result.data['data'];
        log('load complete');
        try {
          addPosterDataToSqlite(allData);
          log('data updated');
        } catch (e1) {
          log('sqlite error');
          log(e1);
        }
        var width = phoneSize.width;
        var all_width = width - 20;
        var item_width = (all_width / 2) - 100;

        for (var i = 0; i < allData.length; i++) {
          double poster_width = allData[i]['poster_width'].toDouble();
          double poster_height = allData[i]['poster_height'].toDouble();
          double currentItemHeight = (poster_height * 175 / poster_width);
          allData[i]['currentItemHeight'] = currentItemHeight;
        }

        if (page == 0) {
          oldItems = allData;
        } else {
          for (var i = 0; i < allData.length; i++) {
            oldItems.add(allData[i]);
          }
          allData = oldItems;
        }

        itemWidth = item_width;
        posterItems = allData;
        setState(() {});
        log('before generate');
        if (page > 0) {
          generateItems();
        }
      }
      // ignore: empty_catches
    } catch (e) {
      log('home page');
      log(e);
    }
    page++;
    setState(() {});
    Global.hideLoading(context);
  }

  void loadData() async {
    try {
      getSwipers();
    } catch (e) {
      log('getSwiper error');
      log(e);
    }
    try {
      getOtherData();
    } catch (e) {
      log('getOtherData error');
      log(e);
    }
    try {
      getItems();
    } catch (e) {
      log('getItems error');
      log(e);
    }
  }
 

  getImage(url) {
    // log('url:' + url);
    try {
      // return NetworkImage(url);
      return CachedNetworkImage(
        // 加载网络图片过程中显示的内容 , 这里显示进度条
        placeholder: (context, url) {
          // return CircularProgressIndicator();
          return Container();
        },
        // 网络图片地址
        imageUrl: url,
        fit: BoxFit.fill,
      );
    } catch (e) {
      log(e.toString());
      // log('enter catch exception start:' + url);
      // var defaultUrl = '${Global.baseUrl}mini/images/fontStyle.png';
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    // Size size = MediaQuery.of(context).size;
    if (widget.desktop) {
      return Scaffold(
        // appBar: AppBar(
        //   title: Text('首页'),
        // ),
        appBar: AppBar(
          title: Text(
            Global.trans('home', 'home_page'),
            style: TextStyle(
              fontSize: 18,
              color: Colors.white,
              fontFamily: Global.baseFont,
            ),
          ),
          centerTitle: true,
          elevation: 20.0,
          backgroundColor: Global.appBarColor,
        ),
        key: _scaffoldKey,
        body: bodyView(),
      );
    } else {
      return Scaffold(
        // appBar: AppBar(
        //   title: Text('首页'),
        // ),
        appBar: AppBar(
          title: Text(
            "باش بەت",
            style: TextStyle(
              fontSize: 18,
              color: Colors.black,
              fontFamily: Global.baseFont,
            ),
          ),
          centerTitle: true,
          elevation: 20.0,
          backgroundColor: Global.appBarColor,
        ),
        key: _scaffoldKey,
        body: bodyView(),
      );
    }
  }

  bodyView() {
    double categoryHeight = 90;
    double swiperHeight = 200;

    ScrollController scrollController = new ScrollController();
    scrollController.addListener(() {
      //监听滚动事件，打印滚动位置
      scrollController.addListener(() async {
        // log(scrollController.offset); //打印滚动位置
        if (scrollController.position.pixels >
            scrollController.position.maxScrollExtent - 40) {
          log('reach bottom');
        }
      });
    });
    var a = SingleChildScrollView(
      controller: scrollController,
      child: Column(
        children: [
          //swiper

          SizedBox(
            height: swiperHeight,
            child: getSwiperControl(),
          ),
          //category
          SizedBox(
            height: categoryHeight,
            child: generateCategory(categoryHeight),
          ),
          //list
          Container(
            color: const Color.fromARGB(25, 64, 64, 64),
            // height: contentHeight,
            margin:
                const EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 10),
            child: SingleChildScrollView(
              child: generateItems(),
            ),
          ),
        ],
      ),
    );

    return a;
  }

  Widget generateItems() {
    return MasonryGridView.count(
      // 展示几列
      crossAxisCount: 2,
      // 元素总个数
      itemCount: posterItems.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) => waterCard(index),
      // 纵向元素间距
      mainAxisSpacing: 10,
      // 横向元素间距
      crossAxisSpacing: 10,
      //本身不滚动，让外面的singlescrollview来滚动
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    );
  }

  Widget waterCard(int index) {
    double height = posterItems[index]['currentItemHeight'];
    var url = posterItems[index]['poster_url'];

    return GestureDetector(
      child: Container(
        height: height,
        decoration: ShapeDecoration(
          // image: DecorationImage(
          //   //设置背景图片

          //   image: getImage(url),
          //   fit: BoxFit.fill,
          // ),
          //设置圆角
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadiusDirectional.circular(10)),
        ),
        child: getImage(url),
      ),
      onTap: () {
        // gotoEditor(posterItems[index]['id'].toString());
      },
    );
  }

  generateCategory(categoryHeight) {
    var phoneSize = MediaQuery.of(context).size;

    //app/posters/getTypes?page=0
    // var url =
    //     'https://elan-1310487162.cos.ap-chengdu.myqcloud.com//images/名片.png';
    var a = Row(
      children: [
        Container(
          margin: const EdgeInsets.only(left: 20, right: 20),
          height: categoryHeight,
          width: phoneSize.width - 40,
          child: Row(
            children: posterTypes,
          ),
        ),
      ],
    );

    return a;
  }

  getSwiperControl() {
    return Swiper(
        itemCount: swipers.length,
        loop: true,
        autoplay: true,
        key: UniqueKey(),
        itemBuilder: (BuildContext context, int index) {
          return swipers[index];
        });
  }
}
